package com.dkakunsi.monev.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.dkakunsi.monev.entity.Indikator;
import com.dkakunsi.monev.entity.Kegiatan;
import com.dkakunsi.monev.util.MonevDataException;

@Repository("IndikatorHibernateRepository")
public class IndikatorDao extends GenericDao<Indikator> {
	@SuppressWarnings("unchecked")
	public List<Indikator> get(Kegiatan kegiatan) throws MonevDataException {
		Query query = getSession().createQuery("SELECT i FROM Indikator i WHERE i.kegiatan = :kegiatan");
		query.setParameter("kegiatan", kegiatan);
		
		return checkNull(query.list());
	}

	@Override
	public void save(Indikator i) {
		super.save(isExist(i));
	}
	
	@SuppressWarnings("unchecked")
	protected Indikator isExist(Indikator i) {
		Query query = getSession().createQuery("SELECT i FROM Indikator i WHERE i.kegiatan = :kegiatan AND i.nama = :nama");
		query.setParameter("kegiatan", i.getKegiatan());
		query.setParameter("nama", i.getNama());
		
		try {
			List<Indikator> ls = checkNull(query.list());
			if(ls.size() <= 0)
				throw new MonevDataException();
			
			Indikator i2 = ls.get(0);
			i2.setProgres(i.getProgres());
			return i2;
		} catch (MonevDataException e) {
			return i;
		}
	}
}
